package com.example.interceptors;

import com.example.utils.JwtUtil;
import com.example.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

//请求拦截
@Component

public class LoginInterceptor implements HandlerInterceptor {

    public boolean perHandle(HttpServletRequest request, HttpServletResponse response,Object handler) throws Exception {
        //令牌验证
        String token = request.getHeader("Authorization");
        try{
            Map<String,Object> map = JwtUtil.parseToken(token);
            //把业务数据存储到ThreadLocal中
            ThreadLocalUtil.set(map);

            return true;        //放行
        }catch (Exception e){
            response.setStatus(401);
            return false;       //不放行
        }
    }

    //请求完成
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清空ThreadLocalz中的业务数据
        ThreadLocalUtil.remove();
    }
}
